package com.sj.androidgyrodemo;

import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements SensorEventListener {

	@Override
	protected void onPause() {
		super.onPause();
		sManager.unregisterListener(this);
	}

	@Override
	protected void onResume() {
		super.onResume();
		sManager.registerListener(this, sensor,
				SensorManager.SENSOR_DELAY_GAME,handler);
	}

	private SensorManager sManager;
	private Sensor sensor;
	private TextView dataView;
	private static final int SENSOR_SHAKE=1;
	private int defaultVal = 19;
	private Vibrator vibrator;
	private Handler handler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case SENSOR_SHAKE:
				vibrator.vibrate(200);
				Toast.makeText(MainActivity.this,"摇晃了手机！",Toast.LENGTH_SHORT).show();
				break;

			default:
				break;
			}
		}
		
	};

	 
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		sManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
		vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
		
		sensor = sManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
		if (sensor == null)
			sensor = sManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
		dataView = (TextView) findViewById(R.id.data);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onSensorChanged(SensorEvent event) {
		// TODO Auto-generated method stub
		
		dataView.setText(Math.abs(event.values[0]) + "_" + Math.abs(event.values[1]) + "_"
				+ Math.abs(event.values[2]));
		if(Math.abs(event.values[0])>defaultVal || Math.abs(event.values[1])>defaultVal || Math.abs(event.values[2])>defaultVal){
			Message msg = new Message();
			msg.what = SENSOR_SHAKE;
			handler.sendMessage(msg);
		}

	}

}
